﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.VisualBasic;

namespace KABS_Commander
{
    public partial class KABS_Commander : Form
    {
        private List<string> getModules()
        {
            List<string> result = new List<string>();
            byte[] data = new byte[1024];
            int count = GetPrivateProfileSectionNames(data, 1024, System.AppDomain.CurrentDomain.BaseDirectory + configFileName);

            if (count == 0) return result;
            decodeIniReadBytes(data, count, result);

            return result;
        }

        private void InitializeModule()
        {
            List<string> modules = getModules();
            modules.Sort();

            comboBox_module.Items.Clear();
            comboBox_module.Items.Insert(0, "ALL");
            foreach (string module in modules)
            {
                comboBox_module.Items.Add(module);
            }

            comboBox_module.SelectedIndex = 0;
        }

        private void comboBox_module_SelectionChangeCommitted(object sender, EventArgs e)
        {
            InitializeCommand();
        }

        private void button_addModule_Click(object sender, EventArgs e)
        {
            string path = System.AppDomain.CurrentDomain.BaseDirectory + configFileName;
            string module = Interaction.InputBox("Input new module name", "Add module");

            // Unvalid module
            if (module.Length == 0)
                return;
            // Module name only support a~z, A~Z and punctuations
            // No space!
            if (module.Any<char>(c => (!char.IsLetterOrDigit(c)) && !char.IsPunctuation(c)))
            {
                MessageBox.Show("Module name only support a~z, A~Z and punctuations. \nSpace is not supported!");
                return;
            }

            WritePrivateProfileSection(module, "", path);
            InitializeModule();
            comboBox_module.SelectedIndex = comboBox_module.Items.IndexOf(module);
            InitializeCommand();
        }

        private void button_rmModule_Click(object sender, EventArgs e)
        {
            string path = System.AppDomain.CurrentDomain.BaseDirectory + configFileName;
            string module = comboBox_module.Text;
            DialogResult res = MessageBox.Show("Remove Module [" + module + "]?", "WARNING", MessageBoxButtons.YesNo);

            if (res != DialogResult.Yes)
                return;

            WritePrivateProfileSection(module, null, path);
            InitializeModule();
        }


    }
}